/******
 * 1.引入axios
2.创建axios实例  用axios.create
3.设置baseUrl 和timeOut
4.写请求拦截
5.写响应拦截
6.导出
 */
import axios from 'axios';
import { Dialog } from 'vant';

export const instance = axios.create({
    baseURL: 'http://localhost:3000/',
    timeout: 10000
})

//设置请求拦截
instance.interceptors.request.use(
    (config) => {
        config.headers['Content-Type'] = 'application/json'
        return config
    },
    (err) => {
        // Promise.reject(err)
    }
)
//设置响应拦截
instance.interceptors.response.use(   //响应拦截
    (res) => {
        // if (res.data.code != 200) {
        //     Dialog.alert({ title: "请求异常！ 请联系程序猿", message: res.data.message });
        // }
        return res
    },
    (err) => {
        Dialog.alert({ title: "请求异常！ 请联系程序猿", message: err.message });
        return Promise.reject(err)
    }
)

//封装get和post请求
export async function http (url = '', data = {}, type = 'POST') {
    type = type.toUpperCase()
    if (type == 'GET') {
        const res = await instance.get(url, { params: data })
        return new Promise((resolve, reject) => {
            if (res.status == 200) {
                resolve(res)
            } else {
                reject(res)
            }
        })
    } else if (type == 'POST') {
        const res = await instance.post(url, data)
        return new Promise((resolve, reject) => {
            if (res.status == 200) {
                resolve(res)
            } else {
                reject(res)
            }
        })
    }
}
